package week11;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class CyclicBarrierTest {

	/**
	 * @param args
	 * @throws Exception 
	 * @throws InterruptedException 
	 */
	public static void main(String[] args) throws InterruptedException, Exception {
		CyclicBarrier cb = new CyclicBarrier(3);
		new Thread(new ARunnable(cb)).start();
		new Thread(new BRunnable(cb)).start();
		System.out.println("main prepared");
		cb.await();
		System.out.println("main end");

	}

}

class ARunnable implements Runnable{
	private CyclicBarrier cb;
	
	
	public ARunnable(CyclicBarrier cb) {
		this.cb = cb;
	}


	@Override
	public void run() {
		
		try {
			Thread.sleep(3000);
			System.out.println("A prepared");
			cb.await();
			
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (BrokenBarrierException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		System.out.println("A end");
		
	}
	
}

class BRunnable implements Runnable{
	private CyclicBarrier cb;
	
	
	public BRunnable(CyclicBarrier cb) {
		this.cb = cb;
	}


	@Override
	public void run() {
		
		try {
			Thread.sleep(1000);
			System.out.println("B prepared");
			cb.await();
			
			
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (BrokenBarrierException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		System.out.println("B end");
		
	}
	
}

